package com.example.chenjun.myapplication.net.okhttp;

import android.app.Dialog;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.example.chenjun.myapplication.mvp.TypeUtil;
import com.example.chenjun.myapplication.net.BaseLoader;
import com.example.chenjun.myapplication.net.NetController;
import com.example.chenjun.myapplication.net.netcallback.BaseCallback;
import com.example.chenjun.myapplication.net.netcallback.ParseCallback;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class OkHttpLoader<T> extends BaseLoader<T> {

    private static final Handler H = new Handler(Looper.getMainLooper());
    private Call mCall;
    private BaseCallback<T> mCallback;

    public OkHttpLoader(NetController<T> controller) {
        super(controller);
    }

    public OkHttpLoader(NetController<T> controller, Dialog dialog){
        super(controller,dialog);
    }

    @Override
    public T execute(ParseCallback<T> parseCallback) {
        showLoadingDialog();
        mCall = OkhttpUtil.newCall(mController);
        try {
            Response response = mCall.execute();
            return parseCallback.parse(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            hideLoadingDialog();
        }
        return null;
    }

    @Override
    public void enqueue(final BaseCallback<T> callback) {
        mCall = OkhttpUtil.newCall(mController);
        mCallback = callback;
        OkhttpUtil.newCall(mController);
        showLoadingDialog();
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull final Call call, @NonNull final IOException e) {
                H.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onError(e);
                    }
                });
                hideLoadingDialog();
            }

            @Override
            public void onResponse(@NonNull final Call call, @NonNull final Response response) throws IOException {

                final String content = response.body().string();
                H.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onResponse(callback.parse(content));
                    }
                });
                hideLoadingDialog();
            }
        });
    }

    @Override
    public File downFile() {
        return null;
    }

    @Override
    public void cancel() {
        if (mCall != null) {
            mCall.cancel();
        }
    }

    @Override
    public void retry() {
        if (mCallback == null){
            throw new IllegalStateException("同步请求暂不支持retry");
        }
        enqueue(mCallback);
    }
}
